package cn.zhc.com.utils;


import android.content.Context;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by zhouhongchun on 2017/8/30.
 * 替代asyncTask和handler
 */
public class UtilsRx {

    private static UtilsRx instance;
    private ExecutorService executor;


    private UtilsRx() {
        if(executor==null) {
            executor = Executors.newFixedThreadPool(5);
        }
    }

    public synchronized static UtilsRx getInstance(){
        if(instance==null){
            instance = new UtilsRx();
        }
        return instance;
    }

    public <T> void doAsyncTask(final Context context, final OnAsyncTaskListener<T> mOnAsyncTaskListener) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                T result = mOnAsyncTaskListener.onStart();
                Observable.just(result).subscribeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<T>() {
                            @Override
                            public void call(T result) {
                                if (UtilsOther.checkActivityRunning(context)){
                                    mOnAsyncTaskListener.onNext(result);
                                }

                            }
                        });

            }
        });
        executor.execute(thread);
    }


    public interface OnAsyncTaskListener<T> {
        void onNext(T result);
        T onStart();
    }



}
